home *** CD-ROM | disk | FTP | other *** search
/ ETO Development Tools 1 / ETO Development Tools 1.iso / Essentials / C++ AppleLink Messages / CPlus.Dev$ 4⁄27⁄90 / 0110-Handling Constructor-Apr90 < prev    next >
Encoding:
Text File  |  1990-04-27  |  2.1 KB  |  71 lines  |  [TEXT/GEOL]

  1. Item    4603899                         24-April-90        12:01PDT
  2.  
  3. From:   D0532                           Aidea Systems, Don Park,PRT
  4.  
  5. To:     CPLUS.DEV$                      C++ Interest List--Developers
  6.         CPLUS.APPLE$                    C++ Interest List--Apple Employees
  7.  
  8. Sub:    Handling Constructor Errors?
  9.  
  10. I have been suffering of late due to lack of decent error/exception handling
  11. mechanism in C++.  Rather than boil my brain alone, I would like to get some
  12. input from you guys.
  13.  
  14. One common situation I have is error handling within constructors of classes
  15. with pointer/reference to other objects created by the class.  For example:
  16.  
  17. class AllocatingClass
  18. {
  19. public:
  20.     AllocatingClass ( void )    { buffer = malloc(BUFFERSIZE); }
  21.     ~AllocatingClass ( void )   { free(buffer); }
  22.     Validate ( void )           { return (buffer != NULL); }
  23.     DoSomething ( void )        { // do something with buffer }
  24.  
  25. private:
  26.     void *      buffer;         // Pointer to a block of memory
  27. };
  28.  
  29. main ()
  30. {
  31.     AllocatingClass     c;      // stack instance
  32.     AllocatingClass *   p;      // free store instance
  33.  
  34.     p = new AllocatingClass;
  35.  
  36.     // If malloc() call in the constructor failed, buffer will be NULL yet
  37.     // p will NOT be NULL.  One must make additional call to make sure the
  38.     // object got created properly.
  39.  
  40.     if (c.Validate())
  41.         c.DoSomething();
  42.     if (p->Validate())
  43.         p->DoSomething();
  44.  
  45.     delete p;
  46. }
  47.  
  48. As you can see, this situation is indeed very common.  Is there a better way to
  49. handle this situation?  I think nothing short of an exception handling
  50. mechanism will do.
  51.  
  52. It is interesting to note that the constructor is rebuilt by CFront to
  53. following form:
  54.  
  55.     struct AllocatingClass *
  56. AllocatingClass::AllocatingClass ( register struct AllocatingClass * this )
  57. {
  58.     if (this || (this = ::operator new(sizeof(struct AllocatingClass))))
  59.     {
  60.         this->buffer = malloc(BUFFERSIZE);
  61.     }
  62.     return this;
  63. }
  64.  
  65. It is also interesting to note that none of the C++ books seem to discuss this
  66. problem when a predicate member function like Validate() is as much a part of a
  67. class as constructors and destructor.
  68.  
  69. Don Park
  70.  
  71.